package org.example.json;

import cn.hutool.json.*;
import org.example.entity.User;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class JSONTest {

    public static void main(String[] args) throws Exception {
        test();
        test2();
        test3();
        test4();
        test5();
    }


    //将对象转换为JSON对象
    private static void test() throws ParseException {
        String birthday = "2024-12-12";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        User user = new User("John", 30,sdf.parse(birthday));
        JSONObject jsonObject = new JSONObject(user);
        jsonObject.setDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(jsonObject);
    }

    //使用静态方法将对象转化为json字符串
    private static void test2() {
        User user = new User("John", 30);
        String jsonStr = JSONUtil.toJsonStr(user);
        System.out.println("=====test2=============");
        System.out.println(jsonStr);
    }

    //根据key获取值
    public static void test3(){
        User user = new User("John", 30);
        JSONObject jsonObject = new JSONObject(user);
        System.out.println("=====test3=============");
        System.out.println(jsonObject.getStr("name"));
    }

    //添加key
    public static void test4(){
        User user = new User("John", 30);
        JSONObject jsonObject = new JSONObject(user);
        //值是 数组
        jsonObject.append("gender","male");
        //值是 单个
        jsonObject.putOpt("birthday","2024-12-12");
        jsonObject.putOnce("class","first");
        System.out.println("=====test3=============");
        System.out.println(jsonObject);
    }

    //处理JSON数组
    public static void test5() { // 数组转json
        List<User> userList = new ArrayList<>();
        userList.add(new User("John", 30));
        userList.add(new User("Mary", 25));
        JSONArray jsonArray = new JSONArray(userList);
        System.out.println("=====test5=");
        System.out.println(jsonArray);
    }
}
